import router from '../router/index';
import axios from 'axios';
/**
 * 创建axios实例
 */
const ENV = process.env.NODE_ENV;
const host =              //这个链接是后端启动链接
  ENV === 'development' ? 'http://127.0.0.1:3000' : 'http://api.jingongxiang.xyz';
const service = axios.create({
  baseURL: host,
  timeout: '3000',
});

/**
 * 请求拦截
 */
service.interceptors.request.use((config) => {
  if (config.url.indexOf('register') < 0 && config.url.indexOf('login') < 0) {
    config.headers.authorization = localStorage.getItem('token');
  }
  return config;
});

/**
 * 响应拦截
 */
service.interceptors.response.use((res) => {
  const { code, data, message } = res.data;
  
  if (code === 0) {
    // 如果有data字段返回data，否则返回整个响应数据
    return data || res.data;
  } else {
    ElMessage({
      message: message,
      type: 'error',
    });
    return Promise.reject(new Error(message));
  }
}, (error) => {
  console.error('请求错误:', error);
  ElMessage({
    message: '网络错误，请稍后重试',
    type: 'error',
  });
  if (message === '身份认证失败') {
    router.push('/login');
  }
  return Promise.reject(error);
});

/**
 * 封装请求函数
 */
const request = (options) => {
  if (options.method === 'get') {
    options.params = options.data;
  }
  return service(options);
};

export default request;

